package net.gz01.wallet.web.interceptors;



import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.servlet.http.HttpSession;

import com.jfinal.aop.Interceptor;
import com.jfinal.aop.Invocation;

import net.gz01.util.ZOJson;
import net.gz01.wallet.web.auth.AuthSource;
import net.gz01.wallet.web.auth.Authority;

/**
 * 权限拦截
 * @author 钟展峰
 *
 * 2015年8月24日
 */
public class AuthInterceptor implements Interceptor {

	private static final String ADMIN_ACTION = "/admin";
	private static final String ORG_ACTION = "/org";
	private static Set<String> adminInterceptorUrl = new HashSet<>();
	private static Set<String> orgInterceptorUrl = new HashSet<>();
	private static Set<String> merchInterceptorUrl = new HashSet<>();

	private static List<AuthSource> sidebar_admin_zh_CN = new ArrayList<>();
	private static List<AuthSource> sidebar_org_zh_CN = new ArrayList<>();
	private static List<AuthSource> sidebar_merch_zh_CN = new ArrayList<>();

	public AuthInterceptor() {
		sidebar_admin_zh_CN = ZOJson.parseArray(readSidebar("sidebar_admin_zh_CN.json"), AuthSource.class);
		initInterceptorUrl(sidebar_admin_zh_CN, adminInterceptorUrl);

		sidebar_org_zh_CN = ZOJson.parseArray(readSidebar("sidebar_org_zh_CN.json"), AuthSource.class);
		initInterceptorUrl(sidebar_org_zh_CN, adminInterceptorUrl);

		sidebar_merch_zh_CN = ZOJson.parseArray(readSidebar("sidebar_merch_zh_CN.json"), AuthSource.class);
		initInterceptorUrl(sidebar_merch_zh_CN, adminInterceptorUrl);

		System.out.println("----------------- 初始化菜单成功 -----------------");
		System.out.println("admin size = " + sidebar_admin_zh_CN.size());
		System.out.println("org   size = " + sidebar_org_zh_CN.size());
		System.out.println("merch size = " + sidebar_merch_zh_CN.size());
	}

	@SuppressWarnings("unchecked")
	@Override
	public void intercept(Invocation inv) {
		String requestUrl = inv.getActionKey().replaceFirst("/", "") ;
		String sessionName = "";
		Set<String> interceptorUrl = null;
		if(inv.getActionKey().startsWith(ADMIN_ACTION)){
			sessionName = "ADMIN";
			interceptorUrl = adminInterceptorUrl;
		}else if (inv.getActionKey().startsWith(ORG_ACTION)){
			sessionName = "ORG";
			interceptorUrl = orgInterceptorUrl;
		}else{
			sessionName = "MERCH";
			interceptorUrl = merchInterceptorUrl;
		}
		HttpSession session = inv.getController().getSession();
		inv.getController().setAttr("session", session);
		Set<String> hasUrl = (Set<String>) session.getAttribute(sessionName + Authority.MENU_URL);
		session.setAttribute("sessionName", sessionName);
		//不需要拦截的请求或已经有这个请求的权限
		if(interceptorUrl.contains(requestUrl) == false || hasUrl.contains(requestUrl)){
			session.setAttribute("sessionName", sessionName);
			inv.invoke();
		}else{

		}
	}

	private void initInterceptorUrl(List<AuthSource> sources,Set<String> interceptorUrl){
		for (AuthSource source : sources) {
			List<AuthSource> child = source.getChilds();
			if(child == null || child.size() == 0){
				continue;
			}

			//二级
			for (AuthSource second : child) {
				interceptorUrl.add(second.getValue());
				List<AuthSource> secondChild = second.getChilds();

				if(secondChild == null || secondChild.size() == 0){
					continue;
				}

				//三级
				for (AuthSource third : secondChild) {
					interceptorUrl.add(third.getValue());
				}

			}

		}
	}

	private String readSidebar(String fileName) {
		InputStream inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(fileName);
		BufferedReader reader = null;
		InputStreamReader isr = null;
		StringBuffer sb = new StringBuffer();
		try {
			isr = new InputStreamReader(inputStream, "utf-8");
			reader = new BufferedReader(isr);
			String tempString = null;

			// 一次读入一行，直到读入null为文件结束
			while ((tempString = reader.readLine()) != null) {
				sb.append(tempString);
			}
			reader.close();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (reader != null) {
				try {
					reader.close();
				} catch (IOException e1) {
				}
			}
		}
		return sb.toString();
	}

	public static Set<String> getAdminInterceptorUrl() {
		return adminInterceptorUrl;
	}

	public static Set<String> getOrgInterceptorUrl() {
		return orgInterceptorUrl;
	}

	public static Set<String> getMerchInterceptorUrl() {
		return merchInterceptorUrl;
	}

	public static List<AuthSource> getSidebar_admin_zh_CN() {
		return sidebar_admin_zh_CN;
	}

	public static List<AuthSource> getSidebar_org_zh_CN() {
		return sidebar_org_zh_CN;
	}

	public static List<AuthSource> getSidebar_merch_zh_CN() {
		return sidebar_merch_zh_CN;
	}





}
